

//1.引入声明式导航

import Header from '../../components/Header/Header'

import React, { Component } from 'react'
//2.引入ant库
import { Button, Form, Input, Toast } from 'antd-mobile'

//3.引入登录请求
import { reqlogin } from '../../http/api'


export default class Login extends Component {
    constructor() {
        super()
        //4.初始化数据
        this.state = {
            user: {
                phone: '',
                password: ''
            }
        }
    }

    //6.点击登录按钮发送请求并跳转到首页
    async login() {
        //res接收后端返回数据
        let res = await reqlogin(this.state.user)
        if (res.data.code == 200) {
            //成功消息提醒
            Toast.show({ 
                content: res.data.msg 
            })
            //把值存入到本地存储
            localStorage.setItem('isLogin',JSON.stringify(res.data.list))
            
            //成功后跳转到首页
            this.props.history.push('/index/home')
        }
    }


    //5.input数据绑定user数据
    changeUser(e, key) {
        this.setState({
            user: {
                ...this.state.user,
                //注意：在ant框架中e就是input框的值
                [key]: e
            }
        })
    }


    render() {
        //6.结构赋值获取user数据
        let { user } = this.state
        return (
            <div>
                {/* 登录页面需要显示注册按钮所以需要传值给Header组件 */}
                <Header title='登录' register='register'></Header>
                <Form layout='horizontal' className='app'>
                    <Form.Item label='用户名' name='username'>
                        {/* value与input框的值绑定,并传入event事件和key键名 */}
                        <Input placeholder='请输入用户名' clearable value={user.phone} onChange={e => this.changeUser(e, 'phone')} />
                    </Form.Item>
                    <Form.Item label='密码' name='password'>
                        <Input placeholder='请输入密码' clearable type='password' value={user.password} onChange={e => this.changeUser(e, 'password')} />
                    </Form.Item>
                </Form>
                {/* 点击登录按钮跳转到首页 */}
                <Button block color='primary' onClick={() => this.login()}>
                    登录按钮
        </Button>
                {/* 输出user的值看是否绑定成功 */}
                <div>user:{JSON.stringify(this.state.user)}</div>
            </div>
        )
    }
}
